package com.hjc.oj.judge.codesandbox.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hjc.oj.common.ErrorCode;
import com.hjc.oj.exception.BusinessException;
import com.hjc.oj.judge.codesandbox.CodeSandBox;
import com.hjc.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.hjc.oj.judge.codesandbox.model.ExecuteCodeResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 远程代码沙箱
 */
@Log4j2
@Service
public class RemoteCodeSandBox implements CodeSandBox {


    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱------->");
        //todo 修改远程代码沙箱地址
        String url = "http://localhost:8090/executeCode ";
        System.out.println(url);
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = new String();
        try {
            responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        // 处理响应
    } catch (HttpException e) {
        // 处理HTTP相关异常（如4xx/5xx状态码）
        log.error("HTTP请求失败: {}", e.getMessage());
    } catch (Exception e) {
        // 处理其他异常（如网络超时）
        log.error("请求发生异常: {}", e.getMessage());
    }
        System.out.println(responseStr);
        System.out.println("远程代码沙箱------->结束");
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteSandbox error, message = " + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
